<?php
/* SVN FILE: $Id: scope.php 1839 2008-10-22 12:10:13Z francis $ */
/**
 *
 * Purpose:
 * 1. Find Scope. Limit access to records during find calls. Add scope conditions to limit access.
 * 2. Create scope.
 * 	Automatically fill scoped fields by scope values.
 * 3. Update scope. Allow to update only scoped records.
 * 4. Delete scope. Allow to delete only scoped records.
 */
class ScopeBehavior extends ModelBehavior {
	var $settings = null;
	//var $_model = null;

	function setup(&$model, $config = array()) {
		$settings = array('enabled' => true);

		if (isset($config['scope'])) {
			$settings['scope'] = $config['scope'];
		} else{
			if (isset($config['enabled'])) {
				$settings['scope'] = array();
			} else {
				$settings['scope'] = $config;
			}
		}

		if (isset($config['enabled'])) {
			$settings['enabled']=$config['enabled'];
		}
		$this->settings[$model->name] = $settings;
	}

	function scopeEnable (&$model){
		$this->settings[$model->name]['enabled'] = true;
	}

	function scopeDisable (&$model){
		$this->settings[$model->name]['enabled'] = false;
	}
/**
 * Before find method. Called before all find
 *
 * Set scope filer settings
 *
 * @param AppModel $model
 * @return boolean True to continue, false to abort the save
 */
	function beforeFind(&$model, $cond) {
		if (!$this->settings[$model->name]['enabled']) {
			return true;
		}

		if (!is_array($cond['conditions'])) {
			$cond['conditions'] = array($cond['conditions']);
		}

		foreach ($this->settings[$model->name]['scope'] as $key => $value) {
			$cond['conditions'][$model->name.'.'.$key]=$value;
		}
		return $cond;
	}

	function beforeSave(&$model) {
		$result = true;

		if (!$this->settings[$model->name]['enabled']) {
			return true;
		}

		if (empty($model->data[$model->name][$model->primaryKey])) {
			foreach ($this->settings[$model->name]['scope'] as $key => $value) {
				$model->data[$model->name][$key] = $value;
			}
		} else {
			$data = $model->data;
			$recursive = $model->recursive;
			$oldData = $model->read(null, $model->id);

			foreach ($this->settings[$model->name]['scope'] as $key => $value) {
				if (isset($data[$model->name][$key]) && (($data[$model->name][$key] != $value) || ($model->data[$model->name][$key] != $value))) {
					$result = false;
				}
			}
			$model->data = $data;
			$model->recursive = $recursive;
		}
		return $result;
	}

	function beforeDelete(&$model) {
		if (!$this->settings[$model->name]['enabled']) {
			return true;
		}

		if ($model->id!==false) {
			$curr = $model->read(null,$model->id);
		}

		foreach ($this->settings[$model->name]['scope'] as $key => $value) {
			if ($curr[$model->name][$key] != $value) {
				return false;
			}
		}
		return true;
	}
}
?>